﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;
using Zj.BaiduPicSpider.Sys;
using Zj.BaiduPicSpider.Sys.Enum;
using Zj.BaiduPicSpider.Sys.EnumExtension;

namespace Zj.BaiduPicSpider
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        private void btnSelPath_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dlg = new FolderBrowserDialog();
            dlg.Description = "请选择图片存放的文件夹";
            dlg.SelectedPath = AppDomain.CurrentDomain.BaseDirectory;
            dlg.ShowNewFolderButton = true;

            var drt = dlg.ShowDialog();
            if (drt == DialogResult.OK)
            {
                this.txtSavePath.Text = dlg.SelectedPath;
            }
        }

        private void txtSavePath_TextChanged(object sender, EventArgs e)
        {
            var sPath = this.txtSavePath.Text;
            try
            {
                if (!Directory.Exists(sPath))
                {
                    Directory.CreateDirectory(sPath);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("您没有权限创建该文件夹", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Stop);
                return;
            }
        }

        private void btnDownLoad_Click(object sender, EventArgs e)
        {
            string referer = @"https://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1508814975962_R&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=%E7%BE%8E%E5%A5%B3&f=3&oq=mein&rsp=0";
            var pageNum = this.nudPageNum.Value == 0 ? 1 : Convert.ToInt32(Math.Floor(this.nudPageNum.Value));

            for (int i = 0; i < pageNum; i++)
            {
                string url = GetUrl(pageNum);

                var html = HttpHelper.DownloadHtml(url, referer);
                this.txtLog.Text = html;

                JObject jObj = JObject.Parse(html);
                JArray jArr = (JArray)(jObj["data"]);


                int j = 0;
                foreach (JObject item in jArr)
                {
                    var path = this.txtSavePath.Text.Trim();
                    var imgUrlObj = item["thumbURL"];
                    var ObjURL = string.Empty;
                    var FromURL = string.Empty;
                    if (item["replaceUrl"] != null)
                    {
                        ObjURL = item["replaceUrl"][0]["ObjURL"].ToString();
                        FromURL = item["replaceUrl"][0]["FromURL"].ToString();

                        var img01 = GetImgName(i, j, ObjURL, path);
                        this.txtLog.Text = img01 + "\r\n" + this.txtLog.Text;
                        HttpHelper.DownloadImg(ObjURL, FromURL, img01);
                    }
                    if (imgUrlObj != null)
                    {
                        var imgUrl = imgUrlObj.ToString();
                        var img02 = GetImgName(i, j, imgUrl, path);
                        this.txtLog.Text = img02 + "\r\n" + this.txtLog.Text;
                        HttpHelper.DownloadImg(imgUrl, FromURL, GetImgName(i, j, imgUrl, path));
                    }
                    j++;
                }
            }
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            BindData();
        }


        /// <summary>
        /// 拼接获取请求的Url
        /// </summary>
        /// <returns></returns>
        private string GetUrl(int pageNum)
        {
            var keyword = HttpUtility.UrlEncode(this.txtKeyword.Text.Trim());

            if (string.IsNullOrEmpty(keyword))
            {
                MessageBox.Show("请输入搜索关键词", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
                return "";
            }
            var path = this.txtSavePath.Text.Trim();
            if (string.IsNullOrEmpty(path))
            {
                MessageBox.Show("请选择或者输入图片保存的路径", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
                return "";
            }

            var color = this.cboColor.SelectedValue;
            var size = this.cboSize.SelectedValue;

            var height = string.Empty;
            var width = string.Empty;
            if (this.cbkEnable.Checked)
            {
                height = this.nudHeight.Value.ToString();
                width = this.nudWidth.Value.ToString();
            }
            string url = string.Format(@"https://image.baidu.com/search/acjson?tn=resultjson_com&ipn=rj&ct=201326592&is=&fp=result&queryWord={0}&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=-1&z={1}&ic={2}&word={0}&s=&se=&tab=&width={4}&height={3}&face=0&istype=2&qc=&nc=1&fr=&pn={5}&rn=30&gsm=1e&1508807504609="
, keyword, size, color, height, width, pageNum * 30);
            return url;
        }

        /// <summary>
        /// 初始化数据绑定
        /// </summary>
        private void BindData()
        {
            this.txtSavePath.Text = Path.Combine(AppDomain.CurrentDomain.BaseDirectory ,"App_Data");
            this.txtKeyword.Text = "美女";
            this.nudPageNum.Value = 100;
            BindComobox();
        }


        /// <summary>
        /// 下拉列表绑定枚举
        /// </summary>
        private void BindComobox()
        {
            this.cboColor.DataSource = ColorEnum.Black.GetEnumModels();
            this.cboColor.DisplayMember = "Annotation";
            this.cboColor.ValueMember = "Value";
            this.cboColor.SelectedIndex = 0;

            this.cboSize.DataSource = SizeEnum.All.GetEnumModels();
            this.cboSize.DisplayMember = "Annotation";
            this.cboSize.ValueMember = "Value";
            this.cboSize.SelectedIndex = 0;
        }


        /// <summary>
        /// 图片名称
        /// </summary>
        /// <param name="i"></param>
        /// <param name="j"></param>
        /// <param name="ObjURL"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        private static string GetImgName(int i, int j, string ObjURL, string path)
        {
            return Path.Combine(path, $"{i}_{j}{ObjURL.Substring(ObjURL.LastIndexOf("."))}");
        }


    }
}
